package com.zzyl.controller.manager;


import cn.hutool.core.lang.UUID;
import com.zzyl.base.ResponseResult;
import com.zzyl.file.FileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 上传结果
     * @throws Exception 异常
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    @SneakyThrows //帮组我们将方法try catch 如果有异常,会抛出
    public ResponseResult<String> upload(@RequestPart("file") MultipartFile file) throws Exception {

        // 获得原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获得文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;


        String filePath = fileStorageService.store(fileName, file.getInputStream());

        log.info("文件上传,文件名:{},文件路径:{}", fileName, filePath);

        return ResponseResult.success(filePath);
    }
}